package com.wlr.study.leetcode;

/**
 * @author lrwang
 * @version 1.0
 * @date 2021/6/20 23:56
 */
public class RemoveNthFromEnd {
    //给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode p=head;
        int length=RemoveNthFromEnd.size(head);
        int position=length-n;
        int index=1;
        while (index!=position){
            p=p.next;
            index++;
        }
        p.next=p.next.next;
        return head;
    }
    public static int size(ListNode head){
        int result=0;
        ListNode p=head;
        while (p!=null){
            result++;
            p=p.next;
        }
        return result;
    }

    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        ListNode next1=new ListNode(2);
        ListNode next2=new ListNode(3);
        ListNode next3=new ListNode(4);
        ListNode next4=new ListNode(5);
        head.next=next1;
        next1.next=next2;
        next2.next=next3;
        next3.next=next4;
        System.out.println(RemoveNthFromEnd.size(head));
        ListNode result=removeNthFromEnd(head,2);
        System.out.println(result);
        while (result!=null){
            System.out.println(result.val);
            result=result.next;
        }
    }
}
